package com.example.myapplication.rxjava;

import java.net.SocketException;
import java.net.SocketTimeoutException;

import retrofit2.adapter.rxjava.HttpException;
import rx.Subscriber;

public class SubscriberCallBack<T> extends Subscriber<T> {
    private ApiCallback<T> apiCallback;

    public   SubscriberCallBack(ApiCallback<T> apiCallback) {
        this.apiCallback = apiCallback;
    }

    @Override
    public void onCompleted() {
        apiCallback.onCompleted();
    }

    @Override
    public void onError(Throwable e) {
        e.printStackTrace();
        if (e instanceof HttpException) {
            HttpException httpException = (HttpException) e;
            int code = httpException.code();
            String msg = httpException.getMessage();
            apiCallback.onFailure(code, msg);
        } else if (e instanceof SocketTimeoutException) {
            apiCallback.onFailure(0, "网络连接超时！");
        } else if (e instanceof SocketException) {
            apiCallback.onFailure(0, "网络不给力哦！");
        } else {
            apiCallback.onFailure(0, "数据异常");
        }
        apiCallback.onCompleted();
    }

    @Override
    public void onNext(T t) {
        apiCallback.onSuccess(t);
    }
}
